// 搜索(客户, 资产...)

import React from "react";
import { History, Lifecycle } from "react-router";
import Reflux from "reflux";
import $ from "jquery";

import { SearchStore } from "../store/searchstore.js";
import { SearchActions } from "../action/searchaction.js";
import { GOTOMixin } from "./mixins.jsx"


var PageSearch = React.createClass({
	mixins: [History, Reflux.connect(SearchStore, "data"), GOTOMixin, ],
	getInitialState: function(){
		var vals = {
			query: null, // 查询值
			modkey: "yyb_sf",
			pre: null,
			city: {},
			params: this.props.location.query
		};
		var reg = new RegExp(/#\/(\w+)(\/\w+)?\?(.+)/);
		var res = reg.exec(vals.params.pre);
		if (res == null) {
			vals.pre = "/index";
		} else if (res[2] == undefined) {
			vals.pre = "/" + res[1];
		} else {
			vals.pre = "/" + res[1] + res[2];
		}
		return vals;
	},
	propsType: {
		handleSelectYYB: React.PropTypes.any.isRequired // 选择营业部之后的回调
	},
	componentDidMount: function(){
		SearchActions.fetchData();
		this.resetSliderNav();
	},
	gotoBackPage: function(event) {
		var obj = event.currentTarget;
		this.state.params.yyb_id = obj.id;
		this.state.params.yyb_name = $(obj).text();
		this.state.params.pre = undefined;
		this.history.pushState(null, this.state.pre == undefined ? "/index" : this.state.pre, this.state.params);
	},
	searchQuery: function() {
		var query = $("#query").val();
		query = query == "" ? null : query;
		this.setState({query: query});
	},
	switchMod: function(event) {
		var modkey = event.currentTarget.id
		this.setState({modkey: modkey});
	},
	searchList: function(data){
		var departmentList = new Object();
		for (var key in data) {
			var department = data[key];
			var firstLetter = department[this.state.modkey].toUpperCase();
			if (departmentList[firstLetter] == undefined) {
				departmentList[firstLetter] = {py: null, data: new Array()};
			}
			if (this.state.query == null) {
				departmentList[firstLetter].data.push(department);
			} else {
				var reg = new RegExp(this.state.query);
				if (reg.test(department.yyb_mc) || reg.test(department.yyb_sf)) {
					departmentList[firstLetter].data.push(department);
				}
			}
			if (this.state.modkey == "yyb_sf") {
				departmentList[firstLetter].py = department.pyszm_sf.toUpperCase();
			} else {
				departmentList[firstLetter].py = department.pyszm_yyb.toUpperCase();
			}
		}
		return departmentList;
	},
	showDepartment: function(event) {
		var targetid = event.currentTarget.id;
		this.state.city[targetid] = this.state.city[targetid] == true ? false : true;
		this.setState(this.state.city);
	},
	createKeyList: function(searchList) {
		var keyList = new Array();
		var cityList = {};
		var lsort = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
		if (this.state.modkey == "yyb_sf") {
			for (var key in searchList) {
				var val = searchList[key];
				if (cityList[val.py] == undefined) {
					cityList[val.py] = new Array();
				}
				cityList[val.py].push(key);
			}
			var ssort = new Array();	// 存省市顺序
			lsort.map(function (py) {
				if (cityList[py.toUpperCase()] != undefined) {
					cityList[py.toUpperCase()].map(function (val) {
						ssort.push(val);
					});
				}
			});
			if (this.state.query != null) {
				lsort = ssort;
			}
		}
		for (var i = 0; i < lsort.length; i++) {
			var key = lsort[i].toUpperCase();
			var departmentList = new Array();
			var department = null;
			if (this.state.modkey == "yyb_sf" && cityList[key] != undefined && this.state.query == null) {
				for (var k in cityList[key]) {
					var city = cityList[key][k];
					var dList = new Array();
					for (var k2 in searchList[city].data) {
						department = searchList[city].data[k2];
						dList.push(
							<li key={k2} id={department.yyb_id} onTouchTap={this.gotoBackPage}>{department.yyb_mc}</li>
						);
					}
					departmentList.push(
						<dd key={k} id={city} onTouchTap={this.showDepartment}>{city}
							<ul id={cityList[key][k]+"view"} style={{display: this.state.city[city] == true ? "block" : "none"}}>{dList}</ul>
						</dd>
					);
				}
			} else if (searchList[key] != undefined) {
				for (var k in searchList[key].data) {
					department = searchList[key].data[k];
					departmentList.push(
						<dd key={k} id={department.yyb_id} onTouchTap={this.gotoBackPage}>{department.yyb_mc}</dd>
					);
				}
			} else {
				continue;
			}
			if (departmentList.length > 0) {
				keyList.push(
					<dl key={key}>
						<dt id={key}>{key}</dt>
						{departmentList}
					</dl>
				);
			}
		}
		if (keyList.length <= 0) {
			keyList.push(<dl><dt>没有找到相关数据</dt></dl>);
		}
		return keyList;
	},
	gotoNavTitle: function(event) {
		// 点击ABCD之后的动画
		var target = $(event.currentTarget).attr('alt');
		if ($('.search_list '+target).length > 0) {
			var cOffset = $('.search_list').offset().top;
			var tOffset = $('.search_list '+target).offset().top;

			var headerHeight = $("header#header").outerHeight(true) == null ? 0 : $("header#header").outerHeight(true);
			var searchmainHeight = $("div.search_main").outerHeight(true) == null ? 0 : $("div.search_main").outerHeight(true);
			var sortlistHeight = $("div.sort_list").outerHeight(true) == null ? 0 : $("div.sort_list").outerHeight(true);
			var allheaderHeight = sortlistHeight - searchmainHeight;	// headerHeight 顶部一直停在那里 searchmainHeight 搜索一直停在那里
			// headerHeight由于在search_list外，所以不用加，searchmainHeight在search_list内，所以要减去，sortlistHeight在search_list内，由于滚动时不要显示，所以要加
			var pScroll = (tOffset - cOffset) + allheaderHeight;
			$('.search_list dt').removeClass('selected');
			$(target).addClass('selected');
			$(document.body).animate({scrollTop: pScroll + 'px'}, 500, "swing");
		}
	},
	sliderNav: function(options) {
		// 建旁边ABCD导航
		var defaults = {
			items: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"],
			debug: false,
			height: null,
			arrows: true
		};
		var opts = $.extend(defaults, options);
		var o = $.meta ? $.extend({}, opts, $$.data()) : opts;
		var liElem = new Array();
		for (var i = 0; i < o.items.length; i++) {
			liElem.push(<li key={i}><a alt={"dt#" + o.items[i].toUpperCase()} onTouchTap={this.gotoNavTitle}>{o.items[i]}</a></li>)
		}
		var slider = (
			<div className="slider">
				<div className="slider-nav">
					<ul>{liElem}</ul>
				</div>
			</div>
		);
		return slider;
	},
	resetSliderNav: function() {
		// 设置ABCD导航位置
		var headerHeight = $("header#header").outerHeight(true) == null ? 0 : $("header#header").outerHeight(true);
		var height = $(window).height() - headerHeight;
		$('.slider .slider-nav').css("top", headerHeight);
		$('.slider .slider-nav li a').css("line-height", (height/26) - 6+"px");
	},
	render: function(){
		var data = this.state.data;
		if(data == null){
			return <div></div>;
			data = {};
		}

		var searchList = _.get(data, 'search', new Array());
		searchList = this.searchList(searchList);
		var keyList = this.createKeyList(searchList);
		if (this.state.query == null) {
			var zb = (
				<dl>
					<dt>总部</dt>
					<dd id="10000" onTouchTap={this.gotoBackPage}>平安证券</dd>
				</dl>
			);
		} else {
			var zb = "";
		}
		var sliderNav = this.sliderNav({debug: false, arrows: false});
		return (
		<div id="container" className="container">
		<header id="header">
			<span className="back_btn" onTouchTap={this.goBackward}><i className="icon-angle-left"></i></span>
			<span className="header_title"><span>客户数</span></span>
		</header>
		<div id="page_main">
			<div className="search_main_model">
	            <div className="search_main">
	                <div className="input-group">
	                	<i className="icon-search"></i>
	                    <input type="text" className="form-control" placeholder="营业部名称" id="query" />
	                    <span className="input-group-btn">
	                        <button className="btn btn-default" type="button" onTouchTap={this.searchQuery}>搜索</button>
	                    </span>
	                </div>
	            </div>
				{sliderNav}
	            <div className="search_list">
					{zb}
					{keyList}
	            </div>
	        </div>
		</div>
	</div>);
	}
});


export { PageSearch };